# coding=<encoding utf-8>
import json
def readCSV(path):
    data = []
    f = open(path,'r',encoding='utf-8-sig')
    #获取标题
    line = f.readline()
    titles = line.strip().split(",")
    for line in (f.readlines()):
        cols = line.strip().split(",")
        context = {}
        #加单位
        for index,val in enumerate(cols):
            if titles[index] == "area":
                context[titles[index]] = val+"area"
            elif titles[index] == "quantity":
                context[titles[index]] = val+"quantity"
            else:
                context[titles[index]] = val
        data.append(context)
    f.close()
    return (data,titles)
#去对象数组中的重复 
def setList(array,typeM):
    result=[]
    amap = {}
    for val in array:   #循环遍历列表
        if val[typeM] not in amap: #判断 遍历到的数据是否在列表2中
            result.append({'id':val[typeM]})   #如果不存在添加到新的列表2中
            amap[val[typeM]] = 0
    return result
#获取node 并记录node所在位置
def getNode(data,titles):
    node = []
    for title in titles:
        temp = setList(data,title)
        node+=temp
    for index,val in enumerate(node):
        val['index'] = index
    return node
    '''
    for row in data:
        for key in row:
            val = row[key]
            if val not in nodeMap:
                nodeMap[val] = len(node)
                node.append({'id':val})
    return [node,nodeMap]
    '''
def creatJson(data,titles,jsonPath):
    savejson = {}
    #桑基图数据结构 一个node  一个links
    #获取node且记录node所在位置
    data.sort(key= lambda x:x['type'])
    node = getNode(data,titles)
    savejson['nodes'] = node
    links = []
    #获取map name map
    nameMap = {}
    for index,val in enumerate(data):
        nameMap[val['name']] = ('groupLine%d' %index)
    #获取links
    cnt = 0
    for i in range(len(titles)-1):
        for index,row in enumerate(data):
                links.append({
                    'source': row[titles[i]],
                    'target': row[titles[i+1]],
                    'value': 1,
                    'index': cnt,
                    'type': row['type'],
                    'class': nameMap[row['name']]
                })
                cnt+=1
    savejson['links'] = links
    #获取type的所有种类
    typeM = list(set([val['type'] for val in data]))
    savejson['type'] = typeM
    with open(jsonPath,'w',encoding="utf-8") as f:
        json.dump(savejson,f,ensure_ascii=False)
data,titles = readCSV('桑基图.csv')
creatJson(data,titles,'sankey.json')